﻿var Account = new function () {
    'use strict';
    var that = this;

    /**
     * 发送短信验证码
     * @param {any} e
     * @returns
     */
    this.sendCaptcha = function (e) {
        var $form = $(e).closest('form');
        var phoneNumber = $form.find('input[name="userName"]').val();
        if (!phoneNumber) {
            //alert('请输入手机号码!');
            $('#sms-login .error-info').html('请输入手机号码!');
            return;
        }

        if (!$.com.validValue($.com.regulars.mobilephone, phoneNumber)) {
            //alert('请输入正确的手机号码!');
            $('#sms-login .error-info').html('手机号码格式不正确, 请输入正确的手机号码!');
            return;
        }

        $('#sms-login .error-info').html('');
        $.ajax({
            type: 'POST',
            url: '/api/Account/SendCaptcha?phoneNumber=' + phoneNumber,
            dataType: 'json',
            contentType: 'application/ json',
            success: result => {
                if (result) {
                    //短信发送成功后, 获取验证码的字样换成 60 秒倒计时
                    $('#sms-login .send-btn-link').hide();
                    $('#sms-login .countdown').show();
                    $('#sms-login .error-info').html('');
                    that.countdown();
                } else {
                    //未找到号码时需要提示
                    //alert('当前手机号码还没有在系统中注册, 请先完成注册!');
                    $('#sms-login .error-info').html('当前手机号码还没有在系统中注册, 请先完成注册!');
                }
            },
            error: err => {
                //发送失败(其他情况)时需要提示
                console.log(err);
                if (err.status === 400) {
                    $('#sms-login .error-info').html(err.responseText);
                }
            }
        });
    }

    /**
     * 提交短信验证码
     * @param {any} e
     */
    this.onSubmitCaptcha = function (e) {
        var $form = e.tagName == "FORM" ? $(e) : $(e).closest('form');
        var phoneNumber = $form.find('input[name="userName"]').val();
        if (!phoneNumber) {
            $('#sms-login .error-info').html('请输入手机号码!');
            return false;
        }

        if (!$.com.validValue($.com.regulars.mobilephone, phoneNumber)) {
            //alert('请输入正确的手机号码!');
            $('#sms-login .error-info').html('手机号码格式不正确, 请输入正确的手机号码!');
            return false;
        }

        var $code = $form.find('input[name="code"]');
        if (!$.com.isJqueryObject($code)) {
            $code = $form.find('input[name="password"]');
        }

        if ($.com.isJqueryObject($code)) {
            var code = $code.val();
            if (!$.com.hasValue(code)) {
                $('#sms-login .error-info').html('请输入短信验证码!');
                return false;
            }

            if (code.length !== 6 || Number.isNaN(Number(code))) {
                $('#sms-login .error-info').html('短信验证码不正确, 请输入6位数字验证码!');
                return false;
            }
        }

        return true;
    }

    /**
     * 清除提示
     */
    this.clearErrorInfo = function (e) {
        $($(e).attr('href')).find('.error-info').html('');
    }

    /**
     * 倒计时
     */
    this.countdown = function () {
        let count = 60;
        let interval = setInterval(() => {
            $('#sms-login .countdown').html(count + ' 秒后重试');
            count--;
            if (count == 0) {
                clearInterval(interval);
                $('#sms-login .countdown').hide();
                $('#sms-login .send-btn-link').show();
            }
        }, 1000);
    }

    this.onLogin = function (e) {
        var $form = e.tagName == "FORM" ? $(e) : $(e).closest('form');
        var $errorInfo = $form.find('.error-info');
        var loginType = $form.find('input[name="type"]').val();
        var userName = $form.find('input[name="userName"]').val();
        if (!userName) {
            //alert(`请输入${loginType == 'Password' ? '用户名' : '手机号码'}!`);
            $errorInfo.html(`请输入${loginType == 'Password' ? '用户名' : '手机号码'}!`);
            return false;
        }

        if (loginType === 'Captcha' && !that.onSubmitCaptcha(e)) {
            return false;
        }

        var password = $form.find('input[name="password"]').val();
        if (!password) {
            //alert(`请输入${loginType == 'Password' ? '密码' : '验证码'}!`);
            $errorInfo.html(`请输入${loginType == 'Password' ? '密码' : '验证码'}!`);
            return false;
        }

        //password = sha256(password);
        var $autoLogin = $('input[name="autoLogin"]');
        $autoLogin.val($autoLogin.prop('checked'));
        var returnUrl = Account.getQueryString('ReturnUrl');
        if (returnUrl) {
            $('input[name="returnUrl"]').val(returnUrl);
        }

        $errorInfo.html('');
        //$form.submit();
        localStorage.clear();

        return true;
    }

    this.onLoginSuccess = function (el, data) {
        if (data) {
            app.cache.global.set('user', data);
        }

        location.href = "/Home/Index";
    }

    this.onResetPassword = function () {
        location.href = "/Account/Login";
    }

    this.onLogout = function () {
        $.ajax({
            type: 'GET',
            url: '/api/Account/Logout',
            dataType: 'json',
            contentType: 'application/ json',
            success: () => {
                localStorage.clear();
                location.href = "/Account/Login"
            },
            error: err => {
                console.log(err);
            },
            complete: () => {
                localStorage.clear();
                location.href = "/Account/Login"
            }
        });
    };

    this.getQueryString = function (key) {
        var queryString = location.href.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+", "g"));
        if (queryString && queryString instanceof Array && queryString.length > 0) {
            for (var i = 0; i < queryString.length; i++) {
                var cur = queryString[i];
                cur = cur.substring(1);
                if (cur) {
                    var index = cur.indexOf('=');
                    if (index > 0) {
                        var name = cur.substring(0, index);
                        if (name == key) {
                            return cur.substring(index + 1, cur.length);
                        }
                    }
                }
            }
        }

        return undefined;
    };
}